import React, { useState, useEffect } from'react';
import { Breadcrumb, Table, Switch, Button, Pagination, message } from 'antd';
import { getcategory, updatecategory, delcategory } from "@/api/account";
import style from './type.module.less';

const GoodsCategoryTable = () => {
    const [tableData, setTableData] = useState([]);
    const [total, setTotal] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);

    // 获取商品分类
    const fetchGoodsCategory = async () => {
        try {
            const response = await getcategory({
                currentPage: currentPage,
                pageSize: pageSize
            });
            console.log(response);
            const processedData = response.data.map(item => ({
               ...item,
                disable: true,
                isEditing: false
            }));
            setTableData(processedData);
            setTotal(response.total || processedData.length);
        } catch (error) {
            message.error('获取商品分类失败');
            console.error('获取商品分类失败:', error);
        }
    };

    useEffect(() => {
        fetchGoodsCategory();
    }, [currentPage, pageSize]);

    // 更改商品分类
    const updateGoodsCategory = async (row) => {
        try {
            const response = await updatecategory(row);
            if (response.code === 0) {
                message.success('分类修改成功');
            } else {
                message.error('分类修改失败');
            }
        } catch (error) {
            message.error('分类修改失败');
            console.error('更新商品分类失败:', error);
        }
    };

    // 编辑
    const handleEdit = (index) => {
        const newData = [...tableData];
        newData[index].disable = false;
        newData[index].isEditing = true;
        setTableData(newData);
    };

    // 编辑完成
    const handleEditComplete = (index, row) => {
        const newData = [...tableData];
        newData[index].disable = true;
        newData[index].isEditing = false;
        setTableData(newData);
        updateGoodsCategory(row);
    };

    // 删除分类
    const handleDelete = async (index, row) => {
        try {
            const { code } = await delcategory({ id: row.id });
            if (code === 0) {
                message.success('分类删除成功');
                const newData = [...tableData];
                newData.splice(index, 1);
                setTableData(newData);
            } else {
                message.error('分类删除失败');
            }
        } catch (error) {
            message.error('分类删除失败');
            console.error('删除商品分类失败:', error);
        }
    };

    // 处理每页数量变化
    const handlePageSizeChange = (newPageSize) => {
        setPageSize(newPageSize);
        setCurrentPage(1);
    };

    // 处理当前页码变化
    const handleCurrentPageChange = (newPage) => {
        setCurrentPage(newPage);
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '分类名',
            dataIndex: 'cateName',
            key: 'cateName',
            render: (text, record, index) => (
                record.isEditing ? (
                    <input
                        value={text || ''}
                        onChange={(e) => {
                            const newData = [...tableData];
                            newData[index].cateName = e.target.value;
                            setTableData(newData);
                        }}
                        onKeyUp={(e) => {
                            if (e.key === 'Enter') {
                                handleEditComplete(index, record);
                            }
                        }}
                    />
                ) : (
                    text
                )
            )
        },
        {
            title: '是否启用',
            dataIndex: 'state',
            key: 'state',
            render: (text, record) => (
                <Switch
                    checked={text === 1}
                    onChange={(checked) => {
                        const newRecord = {...record, state: checked ? 1 : 0 };
                        updateGoodsCategory(newRecord);
                    }}
                    disabled={record.disable}
                />
            )
        },
        {
            title: '操作',
            dataIndex: 'id',
            key: 'id',
            render: (_, record, index) => (
                <div>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => handleEdit(index)}
                        style={{ display: record.disable ? 'inline-block' : 'none' }}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => handleEditComplete(index, record)}
                        style={{ display:!record.disable ? 'inline-block' : 'none', marginLeft: 0 }}
                    >
                        完成
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        danger
                        onClick={() => handleDelete(index, record)}
                        style={{ marginLeft: 8 }}
                    >
                        删除
                    </Button>
                </div>
            )
        }
    ];



    return (
        <div className={style.main}>
          
            <div className={style.table}>
                <p className={style.list}>商品分类</p>
                <Table
                    columns={columns}
                    dataSource={tableData}
                    size="middle"
                    rowKey="id"
                    pagination={false}
                />
                <div className={style['demo-pagination-block']}>
                    <Pagination
                        current={currentPage}
                        pageSize={pageSize}
                        pageSizes={[5, 10, 20, 30, 40]}
                        total={total}
                        onChange={handleCurrentPageChange}
                        onShowSizeChange={handlePageSizeChange}
                        showTotal={(total) => `共 ${total} 条`}
                    />
                </div>
            </div>
        </div>
    );
};

export default GoodsCategoryTable;
    